package top.jsjkxyjs.blackbox.common.DatabaseAwareness;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jsjkxyjs.blackbox.entity.Devbind;
import top.jsjkxyjs.blackbox.entity.Event;
import top.jsjkxyjs.blackbox.entity.Exclude;
import top.jsjkxyjs.blackbox.entity.Iot;
import top.jsjkxyjs.blackbox.service.DevBindService;
import top.jsjkxyjs.blackbox.service.EventService;
import top.jsjkxyjs.blackbox.service.ExcludeService;
import top.jsjkxyjs.blackbox.service.IotService;

@Service
public class DatabaseAwareness {
	@Autowired
	ExcludeService excludeService;
	@Autowired
	IotService iotService;
	@Autowired
	EventService eventService;
	@Autowired
	DevBindService devBindService;

	public void perception() throws InterruptedException {
		while (true) {
			Iot iotInfo = iotService.getIotInfo();
			if (iotInfo == null) {
				Thread.sleep(1000);
				continue;
			}
			analysis(iotInfo);
		}
	}

	public void analysis(Iot iot) {
		Devbind userByIot = devBindService.getUserByIot(iot.getDev_id());
		if (!chickStatus(iot, userByIot) && switchState(iot)) {
			Event event = new Event(userByIot.getCarId(), userByIot.getDevId(), iot.getDs_id());
			event = eventService.insertEvent(event);
			Exclude exclude = new Exclude(userByIot.getUserId(), event.getId(), event.getType(), "" + iot.getAt(), String.valueOf(iot.getAt() + 1000 * 60 * 10));
			excludeService.insertExclude(exclude);
		}
		iotService.setIotState(iot);
	}

	public boolean switchState(Iot iot) {
		if ("Fi".equals(iot.getDs_id())) {
			if (Double.parseDouble(iot.getValue()) > 700) {
				return true;
			}
		}
		if ("tem".equals(iot.getDs_id())) {
			if (Double.parseDouble(iot.getValue()) > 100) {
				return true;
			}
		}
		if ("hum".equals(iot.getValue())) {
			return Double.parseDouble(iot.getValue()) > 90;
		}
		return false;
	}

	public boolean chickStatus(Iot iotInfo, Devbind devbind) {
		return excludeService.checkEventFeasible(devbind, iotInfo.getAt());
	}
}
